/*
 * Contains the actual log reader.
 */

package programaobf;

import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author Plamen
 */
public class Report {

    public static final int MAX_FIELDS = 9;
    public File inputFile;
    public File outputFile;
    public String logPattern = "^([\\d.]+) (\\S+) (\\S+) \\[([\\w:/]+\\s[+\\-]\\d{4})\\] \"(.+?)\" (\\d{3}) (.+?) \"([^\"]+)\" \"([^\"]+)\"$";
    public String EOL = System.getProperty("line.separator");

    private String tmp = "";
    private String separator = "|%|";
    private String newLine = "";

    public Report()
    {
	//Debug info:
    }

    public Report(File inputFile) throws IOException
    {
	if(inputFile.exists())
	{
	    this.inputFile = inputFile;
	    this.outputFile = new File(inputFile.getPath() + ".tmp");
	    this.parseFile(this.inputFile, this.outputFile);
	}
	else
	{
	    System.out.println("File " + inputFile.getName() + " doesn't exists!");
	}
    }

    public void print(String str)
    {
	System.out.println(str);
    }

    public void parseFile(File inputFile, File outputFile) throws IOException
    {
	Pattern applyPattern = Pattern.compile(logPattern);
	Matcher matchField = null;
	try
        {
	    // Read instances
	    //File apachelog = new File(fileRead);
            FileInputStream fis = new FileInputStream(inputFile);
            BufferedInputStream bis = new BufferedInputStream(fis);
            DataInputStream dis = new DataInputStream(fis);

	    //
	    // Write instances:
	    //
	    FileWriter fw = null;
	    BufferedWriter out = null;
	    try
	    {
		fw = new FileWriter(this.outputFile);
		out = new BufferedWriter(fw);

		//
		// Clear contents of the file:
		//
		FileOutputStream eraseFile = new FileOutputStream(this.outputFile);
		eraseFile.write((new String()).getBytes());
		eraseFile.close();

		//out.write("");
	    }
	    catch(IOException e)
	    {
		print("Write error: " + e.getMessage());
	    }

            try
            {
                int counter = 1;
                while(dis.available() != 0)
                {
                    counter++;
                        tmp = dis.readLine();
			try
			{

			    matchField = applyPattern.matcher(tmp);
			    //print(matchField.group(1));
			    if(matchField.matches() && (matchField.groupCount() == MAX_FIELDS))
			    {
				//print(matchField.group(1));
				//print(Integer.toString(matchField.groupCount()));
				newLine = "";
				for(int i = 1; i <= matchField.groupCount(); i++)
				{
				    //print(Integer.toString(i));
				    //print(i);
				    separator = "|%|";
				    EOL = "";
				    if(i == 9)
				    {
					separator = "";
					EOL = "\n";
				    }
				    newLine += (matchField.group(i) + separator + EOL);

				}
				//print(newLine);
				matchField.reset();
				out.write(newLine);
			    }
			    else
			    {
				print("RegEx error: File not formatted correctly / Fields number mismatch!");
				System.exit(0);
			    }
			}
			catch(IllegalStateException e)
			{
			    print("RegEx error: " + e.getMessage());
			    System.exit(0);
			}
                } // end while
		out.close();
		print("Job done! File " + this.outputFile + " successfully written!");
            } // end try open file
            catch(IOException e)
            {
                print("Read error: "+e.getMessage());
            }

        }
        catch(FileNotFoundException e)
        {
            print("Read error: " + e.getMessage());
        }
    }

    // Izprashtame za obrabotka kum CSV, PDF, JSON, HTML
    public void exportTo(String format)
    {
	
    }
}
